Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.

题目大意:根据树的先序遍历和中序遍历生成二叉树,返回根节点

题目难度:Medium

/**
 * Created by gzdaijie on 16/6/7
 * 先序遍历的第一值就是子树的根节点,中序遍历中该值左右两边分别是左子树和右子树
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return helper(preorder, 0, inorder, 0, preorder.length);
    }

    private TreeNode helper(int[] preorder, int index1, int[] inorder, int index2, int len) {
        if (len == 0) return null;

        int cnt = 0;
        for (; cnt < len; cnt++) {
            if (inorder[index2 + cnt] == preorder[index1]) break;
        }
        TreeNode root = new TreeNode(preorder[index1]);
        root.left = helper(preorder, index1 + 1, inorder, index2, cnt);
        root.right = helper(preorder, index1 + cnt + 1, inorder, index2 + cnt + 1, len - cnt - 1);
        return root;
    }
}
gzdaijie            updated 2016-06-07 14:18:26

results matching ""

    No results matching ""